let user_img = "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fc-ssl.duitang.com%2Fuploads%2Fitem%2F201503%2F11%2F20150311215235_Jr5JK.thumb.1000_0.jpeg&refer=http%3A%2F%2Fc-ssl.duitang.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1640227971&t=a1b74a040e7ad560e9eb3f36dd29d57b"
import {
  getWeekDate,
  getTime,
} from "/js/util.js";
import {
  createMessageLeft,
  createMessageMiddle,
  createMessageRight,
} from "./createMessageWrap.js";
import {
  createSudentDetailBuy,
  createStudentDetailNoBuy,
} from "./studentDetail.js";
import {
  selectSrcMessageHistory,
  duplicateRemoval,
  selectDstMessageHistory,
  header,
  start_time,
  end_time,
  teacherimg
} from "./lookupHistory.js";
import loading from "/js/loading.js";
import loginRTM from "./rtmToken.js";
let image = [],
  clients = null,
  list = [],
  id = 0,
  quotientSrc,
  offsetSrc,
  teacher_information = [],
  quotientDst,
  offsetDst,
  left_chat_length = 0,
  allSrcCount,
  allDstCount,
  informationArray = [],
  teacherid = null,
  user_id = JSON.parse(localStorage.getItem("user")).user_id;

let createTeacherMessage = async () => {
  return new Promise(async (resolve) => {
    informationArray = []
    await listenerAgora();
    let messageWrap = document.createElement("div");
    messageWrap.className = "message-wrap";
    await getAllHistory();
    if (informationArray.length) {
      teacherid = informationArray[0].teacherid
      user_img = informationArray[0].teacherimg
      messageWrap.appendChild(createMessageLeft());
      messageWrap.appendChild(createMessageMiddle());
      messageWrap.appendChild(createMessageRight());
      $(".body")[0].appendChild(messageWrap);
      createUserChat(informationArray);
      getData()
      await judgeStudentByTeacherCourse(informationArray[0]);
      listListener();
      uploadImageListener();
      uploadContentListener();
      $('.teachername')[0].innerHTML = informationArray[0].teachername
      searchStudent()
    } else {
      messageWrap.innerHTML = `
      <div class='animated fadeIn no-message'>聊天记录暂时未查询到...</div>
    `
      $(".body")[0].appendChild(messageWrap);
    }

    setTimeout(() => {
      $('.message-wrap')[0].style.opacity = 1
      resolve('ok')
    })
  })


}

let searchStudent = () => {
  $('.search-student')[0].addEventListener('keyup', (e) => {
    if (e.keyCode == "13") {
      $('.list-username').each(function () {
        if ($(this)[0].innerText.includes(e.target.value) && e.target.value !== '') {
          $(this)[0].style.color = 'red'
        } else {
          $(this)[0].style.color = 'black'
        }
      })
    }
  })
}

// get user all message history
let getAllHistory = async () => {
  let students = [];
  //发送方
  let source = await selectSrcMessageHistory(0, user_id, "", "desc",user_img);
  //去重
  source = duplicateRemoval(source, "dst");

  //接收方
  let destination = await selectDstMessageHistory(0, "", user_id, "desc",user_img);
  //去重
  destination = duplicateRemoval(destination, "src");

  informationArray = informationArray.concat(source, destination);
  informationArray = informationArray.sort((a, b) => {
    return b.ms - a.ms;
  });
  //去重
  for (let i = 0; i < informationArray.length; i++) {
    for (let j = i + 1; j < informationArray.length; j++) {
      if (
        informationArray[i].src === informationArray[j].dst &&
        informationArray[i].dst === informationArray[j].src
      ) {
        informationArray.splice(j, 1);
      }
    }
  }
  informationArray.forEach((item) => {
    if (item.dst !== user_id && !isNaN(parseInt(item.dst))) {
      students.push(parseInt(item.dst));
    }
    if (item.src !== user_id && !isNaN(parseInt(item.src))) {
      students.push(parseInt(item.src));
    }
  });

  let res = await ajax('student_ergodic_query', {
    listid: students
  }, 'post')

  if (res?.data) {
    teacher_information = res.data.filter(item => {
      return item !== null
    })
    //循环更新图像
    teacher_information.forEach((item, index) => {
      informationArray[index].teacherimg = item.teacherimg
      informationArray[index].teachername = item.name + '（学生）'
    })
  }




};


//get student is buy teacher course
let judgeStudentByTeacherCourse = async (list) => {
  let list2 = await ajax('query_student_goals', {
    studentid: parseInt(teacherid)
  }, 'post') //（学生）购买课程信息
  if (list2?.data?.length) {
    createSudentDetailBuy(list, list2.data[0])
  } else {
    createStudentDetailNoBuy(list)
  }
}

// listen agora channel or user one point one message
let listenerAgora = async () => {
  let { client } = await loginRTM();

  //显示对端发送的消息
  client.on("MessageFromPeer", function (message, peerId, r) {
    let item = {
      content: message.text,
      createTime: getTime(new Date()),
      id: user_id,
      src : peerId,
      teacherimg,
      user_img,
      uid: peerId,
    };
    // createContent(item, id)
    if (peerId === teacherid) {
      createContent(item, id);
    }

    let isinList = false;
    list.forEach((item) => {
      if (item.dst === peerId || item.src === peerId) {
        isinList = true;
      }
    });
    if (!isinList) {
      domAdd(message, peerId, r);
    } else {
      domUpdate(message, peerId, r);
    }
  });

  clients = client;
};

let createContent = (item, id) => {
  let frag2 = document.createDocumentFragment()
  createUserChatDetail(frag2, item, id++)
  $('.middle-center')[0].children[0].appendChild(frag2)
  requestAnimationFrame(() => {
      let length = $('.middle-center')[0].children[0].children.length - 1,
          height = 0
      let scrollHeight = $('.middle-center')[0].children[0].children[length].scrollHeight
      if (image.length) {
          height = image.length * 161
      }
      if (item.content) {
          height += scrollHeight - 10 + 10
      }
      $('.middle-center')[0].scrollTop = $('.middle-center')[0].scrollHeight
      $('.bottom-input')[0].innerHTML = '请输入您的信息'
  })
}

let getData = async () => {
  let r = [],
    r1 = [],
    r2 = [];

  //先去查询最近所有的消息记录 当作这次信息的偏移量 去查找最近的消息记录
  let recentlyChatSource = await $.ajax({
    url: "https://api.agora.io/dev/v2/project/69ee1d0f77224d1897d21a1d3bc56cd4/rtm/message/history/count",
    headers: header,
    async: true, //异步或同步，默认异步
    dataType: "json", //服务器返回类型
    data: {
      source: user_id,
      destination: teacherid,
      start_time,
      end_time,
    },
    type: "get",
  }).then(async (res) => {
    return res.count;
  });

  let recentlyChatDst = await $.ajax({
    url: "https://api.agora.io/dev/v2/project/69ee1d0f77224d1897d21a1d3bc56cd4/rtm/message/history/count",
    headers: header,
    async: true, //异步或同步，默认异步
    dataType: "json", //服务器返回类型
    data: {
      source: teacherid,
      destination: user_id,
      start_time,
      end_time,
    },
    type: "get",
  }).then(async (res) => {
    return res.count;
  });

  allSrcCount = recentlyChatSource;
  allDstCount = recentlyChatDst;
  console.log("src", recentlyChatSource, "dst", recentlyChatDst);
  if (recentlyChatSource > 100) {
    quotientSrc = parseInt(recentlyChatSource / 100);
    offsetSrc = recentlyChatSource - (quotientSrc * 100);
  } else {
    offsetSrc = 0;
  }
  if (recentlyChatDst > 100) {
    quotientDst = parseInt(recentlyChatDst / 100);
    offsetDst = recentlyChatDst - (quotientSrc * 100);
  } else {
    offsetDst = 0;
  }

  r1 = await selectSrcMessageHistory(offsetSrc, user_id, teacherid,'',user_img);
  r2 = await selectDstMessageHistory(offsetDst, teacherid, user_id,'',user_img);
  r = r.concat(r1, r2);
  r = r.sort((a, b) => {
    return a.ms - b.ms;
  });
  initUserChatDetail(r);

};

let listListener = () => {
  $(".bottom-ul-list").each(function (index) {
    $(this).on("click", async function (e) {
      loading.showLoading({
        type: 2,
        tip: "loading...",
      });
      let { index } = e.target.dataset
      if (!index) {
        index = $(e.target)[0].parentElement.dataset.index
      }
      let teachername = JSON.parse(
        $(e.target)[0].parentElement.dataset.teacher
      ).teachername
      teacherid = JSON.parse(
        $(e.target)[0].parentElement.dataset.teacher
      ).teacherid;
      getData();
      $(".middle-ul")[0].innerHTML = "";
      Array.from($(".bottom-ul-list")).forEach((item) => {
        if (item.dataset.index === this.dataset.index) {
          item.className = "bottom-ul-list chat-active";
        } else {
          item.className = "bottom-ul-list ";
        }
      });
      $(".third-right-content")[0] && $(".third-right-content")[0].remove();
      judgeStudentByTeacherCourse(informationArray[index])
      $('.teachername')[0].innerHTML = teachername
      loading.hideLoading();
    });
  });
};

let domUpdate = (message, peerId, r) => {
  $('.bottom-ul-list').each(function (index) {
    let {
      teacher
    } = $(this)[0].dataset
    teacher = JSON.parse(teacher)
    if (teacher.teacherid === peerId) {
      this.children[1].children[1].innerHTML = message.text.includes('img') ? `<div>图片</div>` : message.text
      this.children[1].children[0].children[1].innerText = getWeekDate(r.serverReceivedTs)
    }
  })
}

let domAdd = (message, peerId, r) => {
  left_chat_length = list.length
  list.push({
    content: "6666",
    day: getWeekDate(r.serverReceivedTs),
    dst: user_id,
    message_type: "peer_message",
    ms: r.serverReceivedTs,
    payload: "6666",
    sendtype: "destination",
    src: peerId,
    teacherid: peerId,
    teacherimg: "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fc-ssl.duitang.com%2Fuploads%2Fitem%2F201503%2F11%2F20150311215235_Jr5JK.thumb.1000_0.jpeg&refer=http%3A%2F%2Fc-ssl.duitang.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1640227971&t=a1b74a040e7ad560e9eb3f36dd29d57b",
    teachername: `${peerId}（学生）`
  })
  let frag = document.createDocumentFragment()
  let teacher = {
    teacherid: peerId,
    teachername: peerId + '（学生）',
  }
  teacher = JSON.stringify(teacher)

  let li = document.createElement('li')
  li.setAttribute('data-index', left_chat_length)
  li.setAttribute('sendtype', 'destination')
  li.className = `bottom-ul-list ${left_chat_length === 0 ? 'chat-active' : ''}`
  li.dataset.teacher = teacher

  let img = `<img data-sendtype='destination' data-teacher=${teacher} data-index="${left_chat_length}" width="48" height="48" style="border-radius: 50%;" src="${user_img}"/>`
  let list_detail = `<div class="list-detail" data-sendtype='destination'  data-teacher=${teacher} data-index="${left_chat_length}">
        <div data-sendtype='destination'  data-teacher=${teacher} data-index="${left_chat_length}" style="width: 90%;display: flex;align-items: center;justify-content: space-between;">
            <span class='list-username' style="color: #3C3C3C;" data-sendtype='destination'  data-teacher=${teacher} data-index="${left_chat_length}">${peerId + '（学生）'}</span>
            <span style="color: #3C3C3C;" data-sendtype='destination'  data-teacher=${teacher} data-index="${left_chat_length}">${getWeekDate(r.serverReceivedTs)}</span>
        </div>
        <div data-teacher=${teacher} data-sendtype='destination'  data-index="${left_chat_length}" class='aside-teacher-content'>${message.text}</div>
    </div>`
  li.innerHTML = img + list_detail
  frag.appendChild(li)
  $('.bottom-ul')[0].appendChild(frag)
}

//监听scroll滚动
let scrollMessageListener = () => {
  $('.middle-center')[0].addEventListener('scroll', async (e) => {
    if (e.target.scrollTop === 0) {
      if (offsetSrc > 0) {
        if (offsetSrc > 100) {
          offsetSrc -= 100
        }
        loading.showLoading({
          type: 1,
          tip: "loading..."
        })
        let res = await selectSrcMessageHistory(offsetSrc > 100 ? offsetSrc : 0, user_id, teacherid)
        if (offsetSrc < 100) {
          res = res.splice(0, offsetSrc)
          offsetSrc = 0
        }
        let frag = document.createDocumentFragment()
        res.forEach(item => {
          createUserChatDetail(frag, item)
        })
        $('.chat-other')[0] && $('.chat-other')[0].before(frag)
        loading.hideLoading();
      }
      if (offsetDst > 0) {
        if (offsetDst > 100) {
          offsetDst -= 100
        }
        loading.showLoading({
          type: 1,
          tip: "loading..."
        })
        let res = await selectDstMessageHistory(offsetSrc > 100 ? offsetDst : 0, teacherid, user_id)
        if (offsetDst < 100) {
          res = res.splice(0, offsetDst)
          offsetDst = 0
        }
        let frag = document.createDocumentFragment()
        res.forEach(item => {
          createUserChatDetail(frag, item)
        })
        $('.chat-other')[0] && $('.chat-other')[0].before(frag)
        loading.hideLoading();
      }
      console.log('滑动到最顶部了', offsetSrc, offsetDst)
      console.log('src', allSrcCount, 'dst', allDstCount)
    }
  })
}

let uploadImageListener = () => {
  let upload = $(".upload")[0];
  upload.addEventListener("click", (e) => {
    let input = document.createElement('input');
    input.type = 'file'
    input.accept = 'image/*'
    input.addEventListener("change", async (e) => {
      if (e.target.files[0]) {
        let { url } = await unploadimg(e.target.files[0],1024 * 1024 * 1024);
        let options = {
          enableHistoricalMessaging: true,
          enableOfflineMessaging: true,
        };
        let res = await clients.sendMessageToPeer(
          {
            text: `<img src='${url}' width='100' height='100' />`,
          },
          teacherid,
          options
        );
        if (res) {
          let item = {
            content: `<img src='${url}' width='100' height='100' />`,
            createTime: getTime(new Date()),
            id: user_id,
            user_img,
            src: user_id,
          };
          let frag2 = document.createDocumentFragment();
          createUserChatDetail(frag2, item, id++);
          $(".middle-center")[0].children[0].appendChild(frag2);
          requestAnimationFrame(() => {
            let length = $(".middle-center")[0].children[0].children.length - 1,
              height = 0;
            let scrollHeight =
              $(".middle-center")[0].children[0].children[length].scrollHeight;
            if (image.length) {
              height = image.length * 161;
            }
            if (item.content) {
              height += scrollHeight - 10 + 10;
            }
            $(".middle-center")[0].scrollTop =
              $(".middle-center")[0].scrollHeight;
            $(".bottom-input")[0].innerHTML = "请输入您的信息";
          });
          domUpdate(
            {
              text: `<div>图片</div>`,
            },
            teacherid,
            {
              serverReceivedTs: new Date(),
            }
          );
        }
        input.remove()
      }else{
        input.remove()
      }
    });
    input.click();
  });
}

let createUserChat = (data) => {
  list = data;
  let frag = document.createDocumentFragment();
  for (let i = 0; i < data.length; i++) {
    let teacher = {
      teacherid: data[i].teacherid,
      teachername: data[i].teachername,
    };
    teacher = JSON.stringify(teacher);

    let li = document.createElement("li");
    li.setAttribute("data-index", i);
    li.setAttribute("sendtype", data[i].sendtype);
    li.className = `bottom-ul-list ${i === 0 ? "chat-active" : ""} animated slideInDown`;
    li.dataset.teacher = teacher;

    let img = `<img data-sendtype=${data[i].sendtype} data-teacher=${teacher} data-index="${i}" width="48" height="48" style="border-radius: 50%;" src="${data[i].teacherimg}"/>`;
    let list_detail = `<div class="list-detail" data-sendtype=${data[i].sendtype
      }  data-teacher=${teacher} data-index="${i}">
            <div data-sendtype=${data[i].sendtype
      }  data-teacher=${teacher} data-index="${i}" style="width: 90%;display: flex;align-items: center;justify-content: space-between;">
                <span style="color: #3C3C3C;" class='list-username' data-sendtype=${data[i].sendtype
      }  data-teacher=${teacher} data-index="${i}" class='list-chat-name'>${data[i].teachername
      }</span>
                <span style="color: #3C3C3C;" data-sendtype=${data[i].sendtype
      }  data-teacher=${teacher} data-index="${i}">${data[i].day
      }</span>
            </div>
            <div data-teacher=${teacher} data-sendtype=${data[i].sendtype
      }  data-index="${i}" class='aside-teacher-content'>${data[i].content ? data[i].content : "尚没有信息"
      }</div>
        </div>`;
    li.innerHTML = img + list_detail;
    frag.appendChild(li);
  }
  $(".bottom-ul")[0].appendChild(frag);
}

let initUserChatDetail = (data) => {
  let frag = document.createDocumentFragment();
  for (let i = 0; i < data.length; i++) {
    createUserChatDetail(frag, data[i], i);
  }
  $(".middle-center")[0].children[0].appendChild(frag);
  requestAnimationFrame(() => {
    $(".middle-center")[0].scrollTop = $(".middle-center")[0].scrollHeight;
  });
  scrollMessageListener()
}

let createUserChatDetail = (frag, item, i) => {
  let li = document.createElement("li");
  li.setAttribute("data-index", i);
  li.className = `${item.src == user_id ? 'chat-me' : 'chat-other'}`;
  let img = `<img width="30" height="30" style="border-radius: 50%;" src="${item.src === user_id ? item.teacherimg : item.user_img}" alt=""/>`;
  let wrap = `<div class="chat-wrap">
        <div class="chat-content">${item.payload ? item.payload : item.content}</div>	
        <div class="chat-time">${item.createTime}</div>	
    </div>`;
  li.innerHTML = img + wrap;
  frag.appendChild(li);
};

let uploadContentListener = () => {
  $('.icon-fasong')[0].addEventListener('click', async () => {
    if (!$('.bottom-input')[0].innerText && Array.from($('.bottom-input')[0].children).length === 0) {
      Dreamer.warning('请输入内容')
      return
    }
    let content = document.createElement('div')
    Array.from($('.bottom-input')[0].childNodes).filter((item) => {
      return !item.src
    }).forEach(item => {
      content.appendChild(item)
    })
    if (content) {
      let options = {
        enableHistoricalMessaging: true,
        enableOfflineMessaging: true
      }
      let res = await clients.sendMessageToPeer({
        text: content.innerHTML
      },
        teacherid,
        options
      )
      if (res) {
        let item = {
          content: content.innerHTML,
          createTime: getTime(new Date()),
          id: user_id,
          user_img,
          teacherimg,
          src: user_id
        }
        let frag2 = document.createDocumentFragment()
        createUserChatDetail(frag2, item, id++)
        $('.middle-center')[0].children[0].appendChild(frag2)
        requestAnimationFrame(() => {
          let length = $('.middle-center')[0].children[0].children.length - 1,
            height = 0
          let scrollHeight = $('.middle-center')[0].children[0].children[length].scrollHeight
          if (image.length) {
            height = image.length * 161
          }
          if (item.content) {
            height += scrollHeight - 10 + 10
          }
          $('.middle-center')[0].scrollTop = $('.middle-center')[0].scrollHeight
          $('.bottom-input')[0].innerHTML = '请输入您的信息'
          domUpdate({
            text: content.innerText,
          }, teacherid, {
            serverReceivedTs: new Date()
          })
        })
      }
    }
  })
}


export {
  createTeacherMessage
}